<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/7/25
 * Time: 10:20
 */

namespace App\Tools\Base;

use App\Tools\Aes;
use App\Tools\Base\Common;
use App\Exceptions\ApiException;
use App\Models\Api\User;
use App\Models\Api\Recode;
use Cache,Redis;

/**
 * 客户端auth登录权限基础类库
 * Class Auth
 * @package App\Tools\Base\Common
 */
class Auth extends Common
{
    /**
     * 登录用户的基本信息
     * @var array
     */
    public $user = [];
    public $recode = [];
    public $is_apple_pay = false;
    public $apple_goods = [];
    public $active = [];
    public $redis;// redis实例
    public $is_cached;// redis开关
    public $cache_time;// 缓存有效期


    /**
     * 初始化
     *
     */
    public  function __construct($allowWithoutLogin = false)
    {
        parent::__construct();

       $this->apple_goods = config('apple_pay_goods');

     if ($this->headers['version'] == $this->apple_goods['version'] && $this->headers['app-type'] == $this->apple_goods['app-type']) $this->is_apple_pay = true;
     if (!$allowWithoutLogin &&(empty($this->user) && !isset($request->uid) && !$this->isLogin()))
        {
            throw new ApiException('登录失效', 200, config('code.denied'));
     }
    }

    /**
     * 判定是否登录
     * @return  boolean
     */
    public function isLogin()
    {
         if (!isset($this->headers['access-token']) || $this->headers['access-token'] == '') return false;
        // access-token AES解密
        $accessUserToken = (new Aes())->decryptWithOpenssl($this->headers['access-token']);

        if (empty($accessUserToken)) return false;

        if (!preg_match('/||/', $accessUserToken)) return false;

        list($token, $id) = explode("||", $accessUserToken);
        $id = intval($id);
        // 账号模拟
        $simulation = config('app.simulation');

        if ($id !== $simulation['from'])
        {
            $map['id'] = $id;
            $map['token'] = $token;
        } else
        {
            $map['id'] = $simulation['to'] ?? $id;
        }

        $userinfo = (new User())->getUserinfo($map);

        if (!$userinfo || empty($userinfo) || $userinfo['forbidden'] == 1) return false;

        // 判定时间是否过期
        if (time() > $userinfo['token_expire'] && isset($map['token'])) return false;

        $this->user = $userinfo;

        return true;
    }


    /**
     * 获取档案
     * @param int $rid1
     * @param int $rid2 【可选】
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws ApiException
     */
    public function getRecode(int $rid1 = 0,int $rid2 = 0)
    {
        $recode2 = null;

        try
        {
            if($rid1 > 0)
            {
                $recode1 = Recode::where(['id' => $rid1, 'uid' => $request->uid])
                    ->first(['id','uid','name','type','year','month','day','hour','minute','timezone','long_deg','long_min','ew','lat_deg','lat_min','ns','is_summer','comments']);


            }
            else
            {
                $recode1 = Recode::where(['isself' => 1, 'uid' => $request->uid])
                    ->first(['id','uid','name','type','year','month','day','hour','minute','timezone','long_deg','long_min','ew','lat_deg','lat_min','ns','is_summer','comments']);
            }
            if($rid2 > 0)
            {
                $recode2 =Recode::where(['id'=>$rid2,'uid'=>$request->uid])
                    ->first(['id','uid','name','type','year','month','day','hour','minute','timezone','long_deg','long_min','ew','lat_deg','lat_min','ns','is_summer','comments']);
            }
        }
        catch (\Exception $e)
        {


            throw new ApiException('档案信息获取失败',200,0);
        }

       if($rid2 === 0) return $recode1;

        else return [$recode1,$recode2];
    }
}
